package com.liqiye.paymanager.service.payment;

import com.liqiye.paymanager.config.PaymentProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class AirwallexService {

    private final PaymentProperties config;
    private final RestTemplate restTemplate;

    public AirwallexService(PaymentProperties config, RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.config = config;
    }

    /**
     * 获取 Access Token
     */
    public String getAccessToken() {
        String url = config.getAirwallex().getBaseUrl() + "/api/v1/authentication/login";
        HttpHeaders headers = new HttpHeaders();
        headers.set("x-client-id", config.getAirwallex().getClientId());
        headers.set("x-api-key", config.getAirwallex().getApiKey());
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, String>> entity = new HttpEntity<>(headers);
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);


        System.out.println(response.getStatusCode());
        System.out.println(response.getBody());
        System.out.println(response.getBody());

        if (response.getStatusCode().equals(HttpStatus.OK) || response.getStatusCode().equals(HttpStatus.CREATED)) {
            return (String) response.getBody().get("token");
        }
        throw new RuntimeException("Failed to get Access Token");
    }

    public Map<String, Object> createCustomer(){
        String url = config.getAirwallex().getBaseUrl() + "/api/v1/pa/customers/create";

        // 获取 Access Token
        String token = getAccessToken();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        Map<String, Object> body = new HashMap<>();
        //由商家指定的唯一请求 ID。最大长度为 64
        body.put("request_id",UUID.randomUUID().toString());
        //该客户在商家系统中的唯一标识符。最大长度为 64。
        body.put("merchant_customer_id", System.currentTimeMillis());

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
        String customerId = response.getBody().get("id").toString();
        System.out.println("customerId：" + customerId);
        System.out.println(response.getBody());
        return response.getBody();
    }

    /**
     * 创建 PaymentIntent（Apple Pay）
     * @param applePayToken 前端 Apple Pay 调起时，拿到的 Apple Pay 支付令牌
     */
    public Map<String, Object> createPaymentIntent(String requestId, String amount, String currency, String merchantOrderId, String applePayToken) {
        String token = getAccessToken();
        String url = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/create";

        Map<String, Object> body = new HashMap<>();
        body.put("request_id", requestId);  // 幂等性控制。UUID就行
        body.put("amount", amount);
        body.put("currency", currency);
        body.put("merchant_order_id", merchantOrderId);  // 我们系统的业务id
        body.put("return_url", "http://baidu.com");  // 指示 Airwallex 在完成付款后应将购物者重定向到何处

        // pci
//        Map<String, Object> paymentMethod = new HashMap<>();
//        paymentMethod.put("type", "card");
//        HashMap<Object, Object> card = new HashMap<>();
//        card.put("number", "4035501000000008");
//        card.put("expiry_year", "2030");
//        card.put("expiry_month", "03");
//        card.put("cvc", "123");
//        card.put("name", "song lnui");
//        paymentMethod.put("card", card);
//        body.put("payment_method", paymentMethod);

        // Apple Pay
//        Map<String, Object> paymentMethod = new HashMap<>();
//        paymentMethod.put("type", "applepay");
//        // 指定了这个直接扣款（相当于 create intent + confirm intent）
//        HashMap<Object, Object> applepay = new HashMap<>();
//        applepay.put("payment_data_type", "encrypted_payment_token");
//        applepay.put("encrypted_payment_token", applePayToken);
//        paymentMethod.put("applepay", applepay);
//        body.put("payment_method", paymentMethod);


        Map<String, Object> paymentConsent = new HashMap<>();
        //触发后续付款的一方。商家、客户之一。
        paymentConsent.put("next_triggered_by", "merchant");
        body.put("payment_consent", paymentConsent);


        Map<String, Object> customer = createCustomer();
        body.put("customer_id",customer.get("id"));


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
        String intentId = response.getBody().get("id").toString();
        Object clientSecret = response.getBody().get("client_secret");
        System.out.println("intent_id:" + intentId);
        System.out.println("client_secret:" + clientSecret);


//        String geturl = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/" + intentId;
//        ResponseEntity<Map> getresponse = restTemplate.exchange(geturl, HttpMethod.GET, entity, Map.class);
//        System.out.println(getresponse);


        return response.getBody();
    }




    /**
     * 确认 PaymentIntent
     */
    public Map<String, Object> confirmPaymentIntent(String paymentIntentId) {
        String token = getAccessToken();
        String url = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/" + paymentIntentId + "/confirm";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Void> entity = new HttpEntity<>(headers);

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
        return response.getBody();
    }


    /**
     * 续费
     */
    public Map<String, Object> renew(String paymentIntentId, String paymentConsentId, String customerId) {
        String token = getAccessToken();

        // 创建 intent
        String createUrl = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/create";
        Map<String, Object> body = new HashMap<>();
        body.put("request_id", UUID.randomUUID().toString());  // 幂等性控制。UUID就行
        body.put("amount", "55");
        body.put("currency", "USD");
        body.put("merchant_order_id", "1111");  // 我们系统的业务id
        body.put("return_url", "http://baidu.com");  // 指示 Airwallex 在完成付款后应将购物者重定向到何处
        body.put("customer_id",customerId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> response = restTemplate.exchange(createUrl, HttpMethod.POST, entity, Map.class);
        System.out.println(response.getBody());


        // confirm intent
        String confirmUrl = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/" + paymentIntentId + "/confirm";
        HttpEntity<Void> confirmEntity = new HttpEntity<>(headers);
        ResponseEntity<Map> confirmResponse = restTemplate.exchange(confirmUrl, HttpMethod.POST, confirmEntity, Map.class);
        System.out.println(confirmResponse.getBody());


        return response.getBody();
    }


    public Map<String, Object> refund(){
        String token = getAccessToken();
        String refundUrl = config.getAirwallex().getBaseUrl() + "/api/v1/pa/refunds/create";
        Map<String, Object> body = new HashMap<>();
        body.put("request_id", UUID.randomUUID().toString());  // 幂等性控制。UUID就行
        body.put("amount", "55");
        body.put("payment_intent_id", "");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> response = restTemplate.exchange(refundUrl, HttpMethod.POST, entity, Map.class);
        System.out.println(response.getBody());
        return response.getBody();
    }





    // ===================================== 订阅付款 =============================================

    // 首次授权，创建 PaymentIntent（setup_future_usage=off_session）
    public Map<String, Object> createSetupPaymentIntent(String merchantOrderId, Map<String, Object> paymentMethod) {
        String token = getAccessToken();

        String url = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/create";

        Map<String, Object> body = new HashMap<>();
        body.put("request_id", UUID.randomUUID().toString());
        body.put("merchant_order_id", merchantOrderId);
        body.put("amount", "10");
        body.put("currency", "USD");
        body.put("payment_method", paymentMethod);
        body.put("setup_future_usage", "off_session");
        body.put("capture_method", "manual"); // 只授权不扣款
        body.put("return_url", "https://your-domain.com/payment-return"); // 3DS验证完成回调地址

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> resp = restTemplate.postForEntity(url, entity, Map.class);
        return resp.getBody();
    }

    // 确认 PaymentIntent（可能返回3DS跳转URL）
    // 会返回 paymentMethodId
    public Map<String, Object> confirmSetupPaymentIntent(String paymentIntentId) {
        String token = getAccessToken();

        String url = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/" + paymentIntentId + "/confirm";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Void> entity = new HttpEntity<>(headers);
        ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
        return resp.getBody();
    }

    // 周期扣款，创建并确认 PaymentIntent（off_session = true）
    public Map<String, Object> createAndConfirmOffSessionPaymentIntent(String merchantOrderId, String paymentMethodId, String amount, String currency) {
        String token = getAccessToken();

        String urlCreate = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/create";

        Map<String, Object> bodyCreate = new HashMap<>();
        bodyCreate.put("request_id", UUID.randomUUID().toString());
        bodyCreate.put("merchant_order_id", merchantOrderId);
        bodyCreate.put("amount", amount);
        bodyCreate.put("currency", currency);
        bodyCreate.put("payment_method", Map.of("id", paymentMethodId));
        bodyCreate.put("off_session", true); // 标记用户不在场自动扣款

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Map<String, Object>> entityCreate = new HttpEntity<>(bodyCreate, headers);
        ResponseEntity<Map> respCreate = restTemplate.postForEntity(urlCreate, entityCreate, Map.class);

        if (respCreate.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException("创建周期扣款PaymentIntent失败");
        }

        Map bodyResp = respCreate.getBody();
        String paymentIntentId = (String) bodyResp.get("id");

        // 确认PaymentIntent
        String urlConfirm = config.getAirwallex().getBaseUrl() + "/api/v1/pa/payment_intents/" + paymentIntentId + "/confirm";
        HttpEntity<Void> entityConfirm = new HttpEntity<>(headers);
        ResponseEntity<Map> respConfirm = restTemplate.exchange(urlConfirm, HttpMethod.POST, entityConfirm, Map.class);

        return respConfirm.getBody();
    }

















}
